package top.ahzy.seobench.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.ahzy.seobench.service.ExtendService;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@Service
public class ExtendServiceImpl implements ExtendService {

    @Autowired
    Executor asyncExecutor;

    @Override
    public List<Integer> portScaner() {
        String host = "www.ahzy.top";
        int startPort = 1;
        int endPort = 10000;
        // 约246秒完成
        return scanOpenPorts(host, startPort, endPort);
    }

    public List<Integer> scanOpenPorts(String host, int startPort, int endPort) {
        // 初始化倒计时器
        CountDownLatch latch = new CountDownLatch(endPort - startPort + 1);
        Collections Collections = null;
        AtomicReference<List<Integer>> openPortList = new AtomicReference<>(java.util.Collections.synchronizedList(new ArrayList<>()));
        for (int port = startPort; port <= endPort; port++) {
            int finalPort = port;
            asyncExecutor.execute(() -> {
                try (Socket socket = new Socket()) {
                    socket.connect(new InetSocketAddress(host, finalPort), 1000); // 设置超时时间
                    openPortList.updateAndGet(list -> {
                        list.add(finalPort);
                        return list;
                    });
                    System.out.println("端口 " + finalPort + " 开放");
                } catch (Exception e) {
                    // 端口未开放，可以记录日志或忽略
                    // log.info("端口 " + finalPort + " 未开放");
                } finally {
                    latch.countDown();
                }
            });
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            log.error("等待倒计时器归零时发生中断: " + e.getMessage());
            Thread.currentThread().interrupt(); // 恢复中断状态
        }

        return openPortList.get();
    }


}
